package com.icode.web.ajaxValid;

import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-10-30
 * Time: 上午9:44
 * To change this template use File | Settings | File Templates.
 */
public class UserInfoAjaxValid {

    public static boolean realName(String realName) {
        if (Pattern.matches("[\u4E00-\u9FA5]+||[A-Za-z]+", realName)) {
            return true;
        }
        return false;
    }

    public static boolean email(String email) {
        if (Pattern.matches("[\\w[\\.-]]+@[\\w]+\\.com", email)) {
            return true;
        }
        return false;
    }

    public static boolean idCard(String idCard) {
        boolean flag = true;
        if (Pattern.matches("[\\d]{17}[\\w]{1}|[\\d]{15}", idCard)) {
            if (Pattern.matches("[\\d]{17}[\\w]{1}", idCard)) {
                if (!idCardValidate(idCard)) {
                    flag = false;
                }
            }
        } else {
            flag = false;
        }
        return flag;
    }

    private static boolean idCardValidate(String idCard) {
        String num = lastNum(idCard);
        if (num.equals(idCard.substring(17))) {
            return true;
        }
        return false;
    }


    private static String lastNum(String idCard) {
        String result = "";
        String str = idCard.substring(0, 17);
        char[] array = str.toCharArray();
        int[] data = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum += Integer.parseInt(array[i] + "") * data[i];
        }
        int a = sum % 11;
        switch (a) {
            case 0:
                result = "1";
                break;
            case 1:
                result = "0";
                break;
            case 2:
                result = "x";
                break;
            case 3:
                result = "9";
                break;
            case 4:
                result = "8";
                break;
            case 5:
                result = "7";
                break;
            case 6:
                result = "6";
                break;
            case 7:
                result = "5";
                break;
            case 8:
                result = "4";
                break;
            case 9:
                result = "3";
                break;
            case 10:
                result = "2";
                break;
        }
        return result;
    }

}
